package com.icode.core.model.user;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import javax.persistence.*;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: ZhongGang
 * Date: 15-1-7
 * Time: 下午10:29
 */
@Entity
@DiscriminatorValue(value = "ADMINISTRATOR")
public class Administrator extends User {
    private static final String ROOT = "ROOT";

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "user_id")
    private List<UserRole> roles = new ArrayList<>();

    public Administrator() {
    }

    public Administrator(String username, String password) {
        super(username, password);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (ROOT.equals(this.getUsername())) {
            Set<GrantedAuthority> authorities = new HashSet<>();
            Privilege[] privileges = Privilege.values();
            for (Privilege privilege : privileges) {
                String value = privilege.getGrantedAuthority();
                GrantedAuthority authority = new SimpleGrantedAuthority(value);
                authorities.add(authority);
            }
            return authorities;
        }

        Set<GrantedAuthority> authorities = new HashSet<>();
        for (UserRole role : roles) {
            List<GrantedAuthority> roleAuthorities = role.getAuthorities();
            authorities.addAll(roleAuthorities);
        }
        return authorities;
    }

    @Override
    public boolean isAdministrator() {
        return true;
    }

    public void add(Role role) {
        UserRole userRole = new UserRole(this, role);
        roles.add(userRole);
    }
}
